package cn.edu.lingnan.demo.controller;

import cn.edu.lingnan.demo.entity.Admin;
import cn.edu.lingnan.demo.entity.Student;
import cn.edu.lingnan.demo.entity.StudentQuery;
import cn.edu.lingnan.demo.entity.common.CommonResult;
import cn.edu.lingnan.demo.service.StudentService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;

/**
 * (Student)表控制层
 *
 * @author makejava
 * @since 2020-05-29 21:49:42
 */
@Controller
@RequestMapping("student")
public class StudentController {
    /**
     * 服务对象
     */
    @Resource
    private StudentService studentService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Student selectOne(Integer id) {
        return this.studentService.queryById(id);
    }

    @RequestMapping("toList")
    public String toList(){
        return "user/student_list";
    }
    /**
     * 查询全部信息
     * @param
     * @return 全部信息
     */
    @PostMapping("queryAll")
    @ResponseBody
    public Object queryAll(Integer page, Integer limit, Student bean){
        System.out.println("bean==" + bean);
        //CommonResult类是为了拼成table.json中的数据类型一致
        CommonResult<Student> result = new CommonResult<>();
        IPage<Student> iPage = studentService.queryAllByLimit(page, limit, bean);
        result.setCode(0);
        result.setCount(iPage.getTotal());
        result.setData(iPage.getRecords());
        System.out.println();
        return result;
    }

    @PostMapping("save")
    @ResponseBody
    public Object save(Student bean){
        Boolean result = false;
//        判断添加还是修改
//        通过判断账号是否存在
        if (bean.getId() != null){
            //编辑
            result = studentService.update(bean) > 0;
        }else {
            //添加
            result = studentService.insert(bean).getId() != null;
        }
        return result;
    }
    @PostMapping("deleteById")
    @ResponseBody
    public boolean deleteById(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        studentService.deleteById(Arrays.asList(ids));
        return true;
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model) {
        model.addAttribute("bean", new Student());
        return "user/student_add";
    }

    @RequestMapping("toEdit")
    public String toEdit(Integer id, Model model){
        System.out.println("id==" + id);

        Student bean = studentService.queryById(id);
        model.addAttribute("bean", bean);
        return "user/student_add";
    }
}